import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { GroupDto } from 'src/app/models/sys/group.dto';
import { BehaviorSubject } from 'rxjs';
import { EditMode } from 'src/app/models/enums/edit-mode.enum';
import { FormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms';
import { DictDto } from 'src/app/models/sys/dict.dto';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ApiService } from 'src/app/services/api.service';
import { PageParam } from 'src/app/models/param/page.param';
import { Consts } from 'src/app/consts/consts';
import { AddGroupParam } from 'src/app/models/param/add-group.param';

const GROUP_TYPE_ID = 'groupTypeId';
const GROUP_NAME = 'groupName';
const REMARK = 'remark';
const GROUP_CODE = 'groupCode';

@Component({
  selector: 'app-add-group',
  templateUrl: './add-group.component.html',
  styleUrl: './add-group.component.less'
})
export class AddGroupComponent implements OnInit {
  @Input() modeSubject!: BehaviorSubject<{ mode: EditMode, group?: GroupDto }>;
  @Output() addGroupEvent = new EventEmitter<boolean>();

  modeEnum = EditMode;
  editMode = EditMode.ADD;
  group?: GroupDto;

  addForm!: UntypedFormGroup;
  submitted = false;

  groupTypes: DictDto[] = [];

  constructor(private _api: ApiService,
    private _fb: FormBuilder,
    private _message: NzMessageService) { }

  ngOnInit(): void {
    this.createAddForm();
    this.getGroupTypes();
  }

  createAddForm() {
    this.addForm = this._fb.group({});
    this.addForm.addControl(GROUP_TYPE_ID, new UntypedFormControl(''));
    this.addForm.addControl(GROUP_NAME, new UntypedFormControl('', [Validators.minLength(2), Validators.maxLength(20)]));
    this.addForm.addControl(REMARK, new UntypedFormControl('', [Validators.minLength(2), Validators.maxLength(20)]));
    this.addForm.addControl(GROUP_CODE, new UntypedFormControl('', [Validators.minLength(1), Validators.maxLength(64)]));

    this.modeSubject.subscribe((value) => {
      this.editMode = value.mode;

      if (this.editMode === EditMode.ADD) {
        this.addForm.get(GROUP_NAME)?.addValidators(Validators.required);
        this.addForm.get(GROUP_TYPE_ID)?.addValidators(Validators.required);
      } else {
        this.group = value.group;
        this.initParam(this.group!);
      }
    })
  }

  getGroupTypes() {
    const param = new PageParam();
    param.pageNum = 1;
    param.pageSize = 1000;
    this._api.getGroupTypeList(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK && resp.data) {
        this.groupTypes = resp.data;
      }
    });
  }

  resetModal() {
    this.submitted = false;
  }

  initParam(group: GroupDto) {
    this.addForm.get(GROUP_NAME)?.patchValue(group.groupName);
    this.addForm.get(GROUP_TYPE_ID)?.patchValue(group.groupTypeId);
    this.addForm.get(REMARK)?.patchValue(group.remark);
    this.addForm.get(GROUP_CODE)?.patchValue(group.groupCode);
  }

  get fm() {
    return this.addForm.controls;
  }

  onCreate() {
    this.submitted = true;
    if (!this.addForm.valid) {
      return;
    }

    const param = new AddGroupParam();
    param.groupTypeId = this.addForm.get(GROUP_TYPE_ID)?.value;
    param.groupName = this.addForm.get(GROUP_NAME)?.value;
    param.remark = this.addForm.get(REMARK)?.value;
    param.groupCode = this.addForm.get(GROUP_CODE)?.value;

    this._api.addGroup(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("添加组成功");
        this.resetModal();
        this.addGroupEvent.emit(true);
      } else {
        this._message.warning("添加组失败");
      }
    });
  }

  onUpdate() {
    this.submitted = true;
    if (!this.addForm.valid) {
      return;
    }

    if (this.group == null) {
      this._message.warning("未选中组");
      return;
    }

    const param = new AddGroupParam();
    param.groupName = this.addForm.get(GROUP_NAME)?.value;
    param.groupTypeId = this.addForm.get(GROUP_TYPE_ID)?.value;
    param.groupCode = this.addForm.get(GROUP_CODE)?.value;
    param.remark = this.addForm.get(REMARK)?.value;

    this._api.addGroup(param).subscribe((resp) => {
      if (resp.code == Consts.RESP_OK) {
        this._message.info("添加组成功");
        this.resetModal();
        this.addGroupEvent.emit(true);
      } else {
        this._message.warning("添加组失败 " + resp.message);
      }
    });
  }

  onSubmit(event: UIEvent) {
    event.preventDefault();

    if (this.editMode === EditMode.ADD) {
      this.onCreate();
    } else {
      this.onUpdate();
    }
  }

  onCancel(event: UIEvent) {
    event.preventDefault();

    this.addGroupEvent.emit(false);
  }
}
